<template>
  <div class="profile-container">
    <h1>个人资料</h1>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 用户信息 -->
    <div v-if="!loading && user" class="profile-content">
      <div class="profile-card">
        <h2>基本信息</h2>
        
        <form @submit.prevent="updateProfile" class="profile-form">
          <div class="form-group">
            <label for="username">用户名</label>
            <input 
              type="text" 
              id="username" 
              v-model="userForm.username" 
              class="form-input"
              disabled
            />
          </div>
          
          <div class="form-group">
            <label for="email">邮箱</label>
            <input 
              type="email" 
              id="email" 
              v-model="userForm.email" 
              class="form-input"
              disabled
            />
          </div>
          
          <div class="form-group">
            <label for="name">姓名</label>
            <input 
              type="text" 
              id="name" 
              v-model="userForm.name" 
              class="form-input"
              placeholder="请输入您的姓名"
            />
          </div>
          
          <div class="form-group">
            <label for="bio">个人简介</label>
            <textarea 
              id="bio" 
              v-model="userForm.bio" 
              class="form-textarea"
              placeholder="请输入您的个人简介"
              rows="4"
            ></textarea>
          </div>
          
          <div class="form-actions">
            <button type="submit" class="btn-save" :disabled="saving">
              {{ saving ? '保存中...' : '保存信息' }}
            </button>
          </div>
        </form>
      </div>
      
      <div class="password-card">
        <h2>修改密码</h2>
        
        <form @submit.prevent="updatePassword" class="password-form">
          <div class="form-group">
            <label for="current-password">当前密码</label>
            <input 
              type="password" 
              id="current-password" 
              v-model="passwordForm.currentPassword" 
              class="form-input"
              placeholder="请输入当前密码"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="new-password">新密码</label>
            <input 
              type="password" 
              id="new-password" 
              v-model="passwordForm.newPassword" 
              class="form-input"
              placeholder="请输入新密码"
              required
              minlength="8"
            />
            <p class="input-hint">密码长度至少8位</p>
          </div>
          
          <div class="form-group">
            <label for="confirm-password">确认新密码</label>
            <input 
              type="password" 
              id="confirm-password" 
              v-model="passwordForm.confirmPassword" 
              class="form-input"
              placeholder="请再次输入新密码"
              required
            />
            <p v-if="passwordMismatch" class="input-error">两次输入的密码不一致</p>
          </div>
          
          <div class="form-actions">
            <button 
              type="submit" 
              class="btn-update-password" 
              :disabled="changingPassword || passwordMismatch || !passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword"
            >
              {{ changingPassword ? '更新中...' : '更新密码' }}
            </button>
          </div>
        </form>
      </div>
      
      <div class="stats-card">
        <h2>学习统计</h2>
        
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">{{ stats.documentCount }}</div>
            <div class="stat-label">文档数量</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.cardCount }}</div>
            <div class="stat-label">卡片数量</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.exerciseCount }}</div>
            <div class="stat-label">练习题数量</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.correctRate }}%</div>
            <div class="stat-label">正确率</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.bookmarkCount }}</div>
            <div class="stat-label">收藏数量</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.noteCount }}</div>
            <div class="stat-label">笔记数量</div>
          </div>
        </div>
      </div>
      
      <div class="preferences-card">
        <h2>偏好设置</h2>
        
        <form @submit.prevent="updatePreferences" class="preferences-form">
          <div class="form-group">
            <label>主题</label>
            <div class="theme-options">
              <label class="theme-option">
                <input 
                  type="radio" 
                  v-model="preferencesForm.theme" 
                  value="light"
                />
                <span class="theme-label">浅色</span>
              </label>
              
              <label class="theme-option">
                <input 
                  type="radio" 
                  v-model="preferencesForm.theme" 
                  value="dark"
                />
                <span class="theme-label">深色</span>
              </label>
              
              <label class="theme-option">
                <input 
                  type="radio" 
                  v-model="preferencesForm.theme" 
                  value="system"
                />
                <span class="theme-label">跟随系统</span>
              </label>
            </div>
          </div>
          
          <div class="form-group">
            <label for="card-per-page">每页卡片数量</label>
            <select 
              id="card-per-page" 
              v-model="preferencesForm.cardsPerPage" 
              class="form-select"
            >
              <option value="12">12</option>
              <option value="24">24</option>
              <option value="36">36</option>
              <option value="48">48</option>
            </select>
          </div>
          
          <div class="form-group">
            <label>练习题难度偏好</label>
            <div class="difficulty-options">
              <label class="difficulty-option">
                <input 
                  type="checkbox" 
                  v-model="preferencesForm.difficultyPreferences.easy"
                />
                <span class="difficulty-label easy">简单</span>
              </label>
              
              <label class="difficulty-option">
                <input 
                  type="checkbox" 
                  v-model="preferencesForm.difficultyPreferences.medium"
                />
                <span class="difficulty-label medium">中等</span>
              </label>
              
              <label class="difficulty-option">
                <input 
                  type="checkbox" 
                  v-model="preferencesForm.difficultyPreferences.hard"
                />
                <span class="difficulty-label hard">困难</span>
              </label>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="submit" class="btn-save-preferences" :disabled="savingPreferences">
              {{ savingPreferences ? '保存中...' : '保存设置' }}
            </button>
          </div>
        </form>
      </div>
      
      <div class="danger-zone">
        <h2>危险操作</h2>
        
        <div class="danger-actions">
          <button @click="showLogoutConfirm = true" class="btn-logout">
            退出登录
          </button>
          
          <button @click="showDeleteConfirm = true" class="btn-delete-account">
            删除账号
          </button>
        </div>
      </div>
    </div>
    
    <!-- 退出登录确认对话框 -->
    <div v-if="showLogoutConfirm" class="modal-overlay">
      <div class="modal-content">
        <h3>确认退出登录</h3>
        <p>您确定要退出登录吗？</p>
        
        <div class="modal-actions">
          <button @click="showLogoutConfirm = false" class="btn-cancel">
            取消
          </button>
          <button @click="logout" class="btn-confirm">
            确认退出
          </button>
        </div>
      </div>
    </div>
    
    <!-- 删除账号确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal-content">
        <h3>确认删除账号</h3>
        <p>此操作将永久删除您的账号和所有数据，无法恢复！</p>
        
        <div class="form-group">
          <label for="delete-confirm-password">请输入密码确认</label>
          <input 
            type="password" 
            id="delete-confirm-password" 
            v-model="deleteConfirmPassword" 
            class="form-input"
            placeholder="请输入您的密码"
          />
        </div>
        
        <div class="modal-actions">
          <button @click="cancelDeleteAccount" class="btn-cancel">
            取消
          </button>
          <button 
            @click="deleteAccount" 
            class="btn-delete" 
            :disabled="!deleteConfirmPassword || deletingAccount"
          >
            {{ deletingAccount ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(false);
const error = ref('');
const user = ref(null);
const userForm = ref({
  username: '',
  email: '',
  name: '',
  bio: ''
});
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const preferencesForm = ref({
  theme: 'system',
  cardsPerPage: 12,
  difficultyPreferences: {
    easy: true,
    medium: true,
    hard: true
  }
});
const stats = ref({
  documentCount: 0,
  cardCount: 0,
  exerciseCount: 0,
  correctRate: 0,
  bookmarkCount: 0,
  noteCount: 0
});
const saving = ref(false);
const changingPassword = ref(false);
const savingPreferences = ref(false);
const showLogoutConfirm = ref(false);
const showDeleteConfirm = ref(false);
const deleteConfirmPassword = ref('');
const deletingAccount = ref(false);

// 计算属性
const passwordMismatch = computed(() => {
  return passwordForm.value.newPassword && 
         passwordForm.value.confirmPassword && 
         passwordForm.value.newPassword !== passwordForm.value.confirmPassword;
});

// 生命周期钩子
onMounted(async () => {
  await fetchUserProfile();
  await fetchUserStats();
  await fetchUserPreferences();
});

// 方法
const fetchUserProfile = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await userStore.getCurrentUser();
    
    if (response.success) {
      user.value = response.user;
      
      // 填充表单
      userForm.value = {
        username: user.value.username,
        email: user.value.email,
        name: user.value.name || '',
        bio: user.value.bio || ''
      };
    } else {
      error.value = '获取用户信息失败';
    }
  } catch (err) {
    error.value = '获取用户信息失败';
    console.error('获取用户信息失败:', err);
  } finally {
    loading.value = false;
  }
};

const fetchUserStats = async () => {
  try {
    const response = await userStore.getUserStats();
    
    if (response.success) {
      stats.value = response.stats;
    }
  } catch (err) {
    console.error('获取用户统计信息失败:', err);
  }
};

const fetchUserPreferences = async () => {
  try {
    const response = await userStore.getUserPreferences();
    
    if (response.success) {
      preferencesForm.value = {
        theme: response.preferences.theme || 'system',
        cardsPerPage: response.preferences.cardsPerPage || 12,
        difficultyPreferences: response.preferences.difficultyPreferences || {
          easy: true,
          medium: true,
          hard: true
        }
      };
    }
  } catch (err) {
    console.error('获取用户偏好设置失败:', err);
  }
};

const updateProfile = async () => {
  saving.value = true;
  error.value = '';
  
  try {
    const response = await userStore.updateProfile({
      name: userForm.value.name,
      bio: userForm.value.bio
    });
    
    if (response.success) {
      // 更新本地用户信息
      user.value = {
        ...user.value,
        name: userForm.value.name,
        bio: userForm.value.bio
      };
      
      // 显示成功消息
      alert('个人资料更新成功');
    } else {
      error.value = response.error || '更新个人资料失败';
    }
  } catch (err) {
    error.value = '更新个人资料失败';
    console.error('更新个人资料失败:', err);
  } finally {
    saving.value = false;
  }
};

const updatePassword = async () => {
  if (passwordMismatch.value) return;
  
  changingPassword.value = true;
  error.value = '';
  
  try {
    const response = await userStore.updatePassword({
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    });
    
    if (response.success) {
      // 清空表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      
      // 显示成功消息
      alert('密码更新成功');
    } else {
      error.value = response.error || '更新密码失败';
    }
  } catch (err) {
    error.value = '更新密码失败';
    console.error('更新密码失败:', err);
  } finally {
    changingPassword.value = false;
  }
};

const updatePreferences = async () => {
  savingPreferences.value = true;
  error.value = '';
  
  try {
    const response = await userStore.updatePreferences(preferencesForm.value);
    
    if (response.success) {
      // 显示成功消息
      alert('偏好设置更新成功');
    } else {
      error.value = response.error || '更新偏好设置失败';
    }
  } catch (err) {
    error.value = '更新偏好设置失败';
    console.error('更新偏好设置失败:', err);
  } finally {
    savingPreferences.value = false;
  }
};

const logout = async () => {
  try {
    await userStore.logout();
    router.push('/login');
  } catch (err) {
    console.error('退出登录失败:', err);
  }
};

const cancelDeleteAccount = () => {
  showDeleteConfirm.value = false;
  deleteConfirmPassword.value = '';
};

const deleteAccount = async () => {
  if (!deleteConfirmPassword.value) return;
  
  deletingAccount.value = true;
  error.value = '';
  
  try {
    const response = await userStore.deleteAccount(deleteConfirmPassword.value);
    
    if (response.success) {
      // 退出登录并跳转到登录页面
      await userStore.logout();
      router.push('/login');
    } else {
      error.value = response.error || '删除账号失败';
    }
  } catch (err) {
    error.value = '删除账号失败';
    console.error('删除账号失败:', err);
  } finally {
    deletingAccount.value = false;
  }
};
</script>

<style scoped>
.profile-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  margin-bottom: 2rem;
  color: #333;
}

.loading-container {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

/* 卡片样式 */
.profile-card, 
.password-card, 
.stats-card, 
.preferences-card, 
.danger-zone {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 2rem;
}

.profile-card h2, 
.password-card h2, 
.stats-card h2, 
.preferences-card h2, 
.danger-zone h2 {
  margin-top: 0;
  margin-bottom: 1.5rem;
  color: #333;
  font-size: 1.3rem;
}

/* 表单样式 */
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.form-input, 
.form-textarea, 
.form-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.form-textarea {
  resize: vertical;
}

.form-input:focus, 
.form-textarea:focus, 
.form-select:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.form-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.input-hint {
  margin-top: 0.5rem;
  color: #666;
  font-size: 0.8rem;
}

.input-error {
  margin-top: 0.5rem;
  color: #ff3860;
  font-size: 0.8rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.btn-save, 
.btn-update-password, 
.btn-save-preferences {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  border: none;
}

.btn-save {
  background-color: #4CAF50;
  color: white;
}

.btn-save:hover {
  background-color: #388E3C;
}

.btn-update-password {
  background-color: #2196F3;
  color: white;
}

.btn-update-password:hover {
  background-color: #1976D2;
}

.btn-save-preferences {
  background-color: #9C27B0;
  color: white;
}

.btn-save-preferences:hover {
  background-color: #7B1FA2;
}

.btn-save:disabled, 
.btn-update-password:disabled, 
.btn-save-preferences:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

/* 统计卡片样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}

.stat-item {
  text-align: center;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #2196F3;
  margin-bottom: 0.5rem;
}

.stat-label {
  color: #666;
  font-size: 0.9rem;
}

/* 偏好设置样式 */
.theme-options, 
.difficulty-options {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-top: 0.5rem;
}

.theme-option, 
.difficulty-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.theme-option input, 
.difficulty-option input {
  margin-right: 0.5rem;
}

.theme-label, 
.difficulty-label {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.9rem;
}

.difficulty-label.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty-label.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty-label.hard {
  background-color: #ffebee;
  color: #c62828;
}

/* 危险区域样式 */
.danger-zone {
  border: 1px solid #ffebee;
}

.danger-zone h2 {
  color: #c62828;
}

.danger-actions {
  display: flex;
  gap: 1rem;
}

.btn-logout, 
.btn-delete-account {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  border: none;
}

.btn-logout {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.btn-logout:hover {
  background-color: #e0e0e0;
}

.btn-delete-account {
  background-color: #F44336;
  color: white;
}

.btn-delete-account:hover {
  background-color: #D32F2F;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel, 
.btn-confirm, 
.btn-delete {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
}

.btn-cancel {
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
}

.btn-cancel:hover {
  background-color: #f0f0f0;
}

.btn-confirm {
  background-color: #2196F3;
  color: white;
  border: none;
}

.btn-confirm:hover {
  background-color: #1976D2;
}

.btn-delete {
  background-color: #F44336;
  color: white;
  border: none;
}

.btn-delete:hover {
  background-color: #D32F2F;
}

.btn-delete:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .danger-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style> 